<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Carts;
use App\Models\Cart;
use App\Models\ProductSku;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    /**
     * 我的购物车
     */
    public function index(Request $request)
    {
        return Api::msg('api.cart.index', Carts::collection(Auth::user()->carts));
    }

    /**
     * 添加购物车
     */
    public function store(Request $request)
    {
        $data = $request->all(['id', 'sku']);

        $number = $request->input('number', 1);

        $sku = ProductSku::query()
            ->where('product_id', $data['id'])
            ->where('id', $data['sku'])->first();

        if (!$sku) {
            return Api::msg('api.product.not_found');
        }

        if ($sku->stock < $number) {
            return Api::msg('api.cart.add.failure', ['reason' => "库存不足"]);
        }

        try {
            if ($cart = Cart::query()->where([
                'customer_id' => Auth::id(),
                'product_id' => $data['id'],
                'sku_id' => $sku->id,
            ])->first()) {
                $cart->increment('number', $number);
            } else {
                $cart = Cart::query()->firstOrCreate([
                    'customer_id' => Auth::id(),
                    'product_id' => $data['id'],
                    'sku_id' => $sku->id,
                ]);

                $cart->update([
                    'number' => $number,
                ]);
            }
        } catch (\Exception $exception) {
            return Api::msg('api.cart.add.failure', ['error' => $exception->getMessage()]);
        }

        return Api::msg('api.cart.add.success');
    }

    /**
     * 删除购物车
     */
    public function delete(Request $request)
    {
        $data = $request->all(['ids']);

        $ids = $data['ids'];

        if (!$ids || !$cart_ids = explode(',', $ids)) {
            return Api::msg('api.cart.not_found');
        }

        Cart::query()->where('customer_id', Auth()->id())->whereIn('id', $cart_ids)->delete();

        return Api::msg('api.cart.delete');
    }

    /**
     * 更新购物车数量
     */
    public function update(Request $request)
    {
        $data = $request->all(['id', 'number']);

        $cart = Cart::find((int)$data['id']);

        if (!$cart) {
            return Api::msg('api.cart.not_found');
        }

        try {
            $cart->update([
                'number' => $data["number"],
            ]);
        } catch (\Exception $exception) {
            return Api::msg('api.cart.add.failure');
        }

        return Api::msg('api.cart.add.success', Carts::make($cart));
    }
}
